package com.gitee.melin.bee.core.fs.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.Bucket;
import com.gitee.melin.bee.core.fs.FileSystem;
import com.gitee.melin.bee.core.fs.FsConnectionInfo;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AliyunOssFileSystem implements FileSystem {
    private static final Logger LOGGER = LoggerFactory.getLogger(AliyunOssFileSystem.class);

    @Override
    public String testConnection(FsConnectionInfo connectionInfo) {
        OSS ossClient = new OSSClientBuilder()
                .build(
                        connectionInfo.getEndpoint(),
                        connectionInfo.getSecretAccessKey(),
                        connectionInfo.getSecretAccessKey());

        String bucket = connectionInfo.getBucket();
        if (StringUtils.isNotBlank(bucket)) {
            List<String> buckets = this.queryBuckets(ossClient);
            if (!buckets.contains(connectionInfo.getBucket())) {
                throw new IllegalArgumentException("bucket not exist: " + bucket);
            }
        }

        return "Success";
    }

    @Override
    public List<String> queryBuckets(FsConnectionInfo connectionInfo) {
        OSS ossClient = new OSSClientBuilder()
                .build(
                        connectionInfo.getEndpoint(),
                        connectionInfo.getSecretAccessKey(),
                        connectionInfo.getSecretAccessKey());

        return this.queryBuckets(ossClient);
    }

    private List<String> queryBuckets(OSS ossClient) {
        try {
            return ossClient.listBuckets().stream().map(Bucket::getName).collect(Collectors.toList());
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            throw new RuntimeException("query buckets error: " + e.getMessage(), e);
        }
    }
}
